package org.example.springboot_dynamicdatasource2.mybatisconfig;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@MapperScan(basePackages = "org.example.springboot_dynamicdatasource2.mapper.d4",
        sqlSessionFactoryRef = "d4SqlSessionFactory")
@Configuration
public class D4DatasourceConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DataSource d4DataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    public SqlSessionFactory d4SqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(d4DataSource());
        sqlSessionFactoryBean
                .addMapperLocations(
                         new PathMatchingResourcePatternResolver().getResources("classpath:mapper/d4/*.xml"));
        sqlSessionFactoryBean.setTypeAliasesPackage("org.example.springboot_dynamicdatasource2.entity");
        return sqlSessionFactoryBean.getObject();
    }

}
